package com.yl.ydk.base

import android.content.Context
import com.yl.ydk.utils.L
import com.yl.ydk.view.LoadingDialog
import com.blankj.utilcode.utils.ToastUtils
import rx.Observer

abstract class BaseObserver<T>(private val mContext: Context) : Observer<T?>  {

    private var loadingDialog: LoadingDialog? = null

    init {
        showLoadingDialog()
    }

    override fun onNext(t: T?) {
        dismissLoadingDialog()
        t?.let {
            onSuccess(t)
        } ?: onFailure("服务器处理请求出错")

    }

    override fun onError(e: Throwable) { //服务器错误信息处理
        dismissLoadingDialog()
        onFailure(e, RxExceptionUtil.exceptionHandler(e))
        L.e(RxExceptionUtil.exceptionHandler(e))
        ToastUtils.showLongToastSafe(RxExceptionUtil.exceptionHandler(e))
    }

    override fun onCompleted() {

    }

    private fun onFailure(message: String) {
        ToastUtils.showLongToastSafe(message)
        onFailure(null, message)
    }

    private fun showLoadingDialog() {
        dismissLoadingDialog()
        val builder: LoadingDialog.Builder =
            LoadingDialog.Builder(mContext)
                .setMessage("请稍后 加载中...")
                .setCancelable(true)
        loadingDialog = builder.create()
        loadingDialog?.show()

    }

    open fun dismissLoadingDialog() {
        if (null != loadingDialog && loadingDialog!!.isShowing) {
            loadingDialog?.dismiss()
            loadingDialog = null
        }
    }

    abstract fun onSuccess(result: T?)

    abstract fun onFailure(e: Throwable?, errorMsg: String?)

}